﻿using System.DirectoryServices;
using System.Linq;
using System.Security.Principal;
using System.Text;

namespace AzManPermissions
{
  public class MemberSearchResult
  {
    public MemberSearchResult(SecurityIdentifier sid)
    {
      SID = sid;
    }

    public SecurityIdentifier SID { get; set; }

    public string DistinguishedName { get; set; }

    public string AccountName { get; set; }

    public ResultPropertyCollection Properties { get; set; }

    public override bool Equals(object obj)
    {
      if (obj == null)
        return false;
      if (!(obj is MemberSearchResult))
        return false;
      if (object.ReferenceEquals(obj, this))
        return true;
      return SID.Equals(((MemberSearchResult)obj).SID);
    }

    public override int GetHashCode()
    {
      return SID.GetHashCode();
    }

    internal static readonly string[] commonPropertyNames = new string[] { "objectsid", "objectclass", "distinguishedname", "samaccountname", "adspath" };

    public override string ToString()
    {
      StringBuilder res = new StringBuilder();
      res.AppendFormat("SID={0};", SID).
        AppendFormat("DistinguishedName={0};", DistinguishedName).
        AppendFormat("AccountName={0}", AccountName);
      foreach (string propertyName in Properties.PropertyNames)
      {
        if (commonPropertyNames.Contains(propertyName))
          continue;
        ResultPropertyValueCollection property = Properties[propertyName];
        if (property.Count > 0)
        {
          res.AppendFormat(";{0}=", propertyName);
          for (int i = 0; i < property.Count; i++)
          {
            res.Append(property[i]).Append(',');
          }
          res.Remove(res.Length - 1, 1);
        }
      }
      return res.ToString();
    }
  }
}